package com.aplicacion.apna;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Layout;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
 
public class TabTematica extends Fragment {
	public final static String TAG_TABTEMATICA = "tab1";
	public static final String PREFERENCES = "preferences";
	 
	private ArrayList<Palabra> items;
	private ArrayList<Palabra> tematicas;
	private ArrayList<Palabra> itemsAux;
	Context context = null;
	private ViewGroup viewgroupAux;
	private View parentView;
	private ListView listView = null;
	private ItemListaBaseAdapter listAdapter;
	public boolean pulsado;
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		MenuBueno mainActivity = (MenuBueno) activity;
		items = mainActivity.getDictionary();
		context = activity;
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		context = getActivity();
		pulsado = false;
		
		setRetainInstance(true);
		setHasOptionsMenu(true);
		
	}
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);

		viewgroupAux = container;
		context = getActivity();
		
		parentView = inflater.inflate(R.layout.tab_tematica, container, false);
		
		obtenerTematicas(); 
		pulsado = false;
				
		Collections.sort(tematicas);
		listAdapter = new ItemListaBaseAdapter(context, tematicas,1);
		
		
		listView = (ListView) parentView.findViewById(R.id.listView);
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if(pulsado){
					//pulsado = false;
					//actualizamos el valor "fecha" del objeto que hemos seleccionado y lo guardamos en preferences
					Date now = new Date();
					SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy/HH/mm/ss");			
					String fecha = dateFormat.format(now);
					
					PreferencesApna.saveApnaDictionary(context, itemsAux.get(position).getTematica(), itemsAux.get(position).getPalabra(), fecha);

			        
					itemsAux.get(position).setFecha(now);
					
					Intent i = new Intent(context,	Item.class);
					
					String palabra = itemsAux.get(position).getPalabra();
					String tematica = itemsAux.get(position).getTematica().toLowerCase();
					
					i.putExtra("palabra", palabra);
					i.putExtra("tematica", tematica);
					
					startActivity(i);
					
				}else{
					pulsado = true;
					
					//cambiamos el adaptador, para que nos muestre las palabras dentro de una tematica
					String tematica = tematicas.get(position).getTematica();
					itemsAux = new ArrayList<Palabra>();
					for(int i = 0;i<items.size();i++){
						if(items.get(i).getTematica().equalsIgnoreCase(tematica)){
							itemsAux.add(items.get(i));
						}
					}
					
					view.setOnKeyListener(new OnKeyListener() {
						
						@Override
						public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
							// TODO Auto-generated method stub
							if(arg1 == KeyEvent.KEYCODE_BACK && pulsado){
								Collections.sort(tematicas);
								listAdapter = new ItemListaBaseAdapter(context, tematicas,1);
								listView.setAdapter(listAdapter);
								listAdapter.notifyDataSetChanged();
								pulsado = false;
							}
							return false;
						}
					});
					
					Collections.sort(itemsAux);
					listAdapter = new ItemListaBaseAdapter(context, itemsAux,2);
					listView.setAdapter(listAdapter);
					listAdapter.notifyDataSetChanged();
				}
			}
		});
		
		listView.setAdapter(listAdapter);
		return parentView;
	
	}
	
	
	private boolean estaTematica(String cat){
		boolean encontrado = false;
		int i = 0;
		while(!encontrado && i<tematicas.size()){
			if(tematicas.get(i).getTematica().equalsIgnoreCase(cat)){
				encontrado = true;
			}else{
				i++;
			}
		}
		return encontrado;
	}
	  
	private void obtenerTematicas(){
		tematicas = new ArrayList<Palabra>();
		ArrayList<String> tematicasAlfa = new ArrayList<String>();
		for(int i = 0;i<items.size();i++){
			if(!estaTematica(items.get(i).getTematica())){
				tematicas.add(items.get(i));
				tematicasAlfa.add(items.get(i).getTematica());
			}
		}
		//ordenamos el array de tematicas por orden alfabetico
		Collections.sort(tematicasAlfa);
		for(int i = 0;i<tematicas.size();i++){
			int p = encuentraPalabraConTematica(tematicasAlfa.get(i),i);
			Collections.swap(tematicas, i, p);
		}
	}
	
	private int encuentraPalabraConTematica(String tematica,int pos){
		boolean encontrado = false;
		while(!encontrado && pos<tematicas.size()){
			if(tematicas.get(pos).getTematica().equalsIgnoreCase(tematica)){
				encontrado = true;
			}else{
				pos++;
			}
		}
		return pos;
	}
	
	public void refresh(){
		   FragmentManager manager = getActivity().getSupportFragmentManager();
           FragmentTransaction ft = manager.beginTransaction();
           Fragment newFragment = this;
           this.onDestroy();
           ft.remove(this);
           ft.replace(viewgroupAux.getId(),newFragment);
            //container is the ViewGroup of current fragment
           ft.addToBackStack(null);   
           ft.commit();
		
		
	}
	
}
